import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './earn.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Swiper, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";

import icon_earn_withdraw from '@/assets/icon_earn_withdraw.png'
import icon_receive from '@/assets/icon_receive.png'
import icon_earn_invite from '@/assets/icon_earn_invite.png'
import icon_earn_level_1 from '@/assets/icon_earn_level_1.png'
import icon_earn_level_2 from '@/assets/icon_earn_level_2.png'
import icon_earn_level_3 from '@/assets/icon_earn_level_3.png'
import icon_earn_level_4 from '@/assets/icon_earn_level_4.png'
import icon_nav_menu from "@/assets/icon_nav_menu.png"
import icon_nav_add_app from '@/assets/icon_nav_add_app.png'

import NavigateBar from "@/components/NavigateBar";
import BottomTabBar from "@/components/BottomTabBar/bottomTabBar";
import { getInviteFriendEarn, getRechargeIncomeConfig, getTransferInEarn } from "@/store/actions/user";
import { EarnLevel } from "./earnLevel";
import { getCoinInfo } from "@/utils/storage";
import { toPercentageString } from "@/utils/utils";
import AddToHomeDialog from "@/components/AddToHomeDialog/AddToHomeGifDialog";
import { LangEn } from "@/utils/langEn";

/**
 * 登录页
 */
export default function Earn() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);

    // 当前 币
    const [curCoin, setCurCoin] = useState({})

    // 当前 邀请好友收益
    const [curInviteEarn, setCurInviteEarn] = useState({})

    // 当前 level 列表
    const [curLevelList, setCurLevelList] = useState([])
    let curLevelListTemp = [];

    // 当前 scroll index
    const [curScrollIndex, setCurScrollIndex] = useState(0)

    // 当前 wallet
    const [curWallet, setCurWallet] = useState({})

    // 文案翻译
    const [curLang, setCurLang] = useState(LangEn);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        // 获取当前币
        const coinInfo = getCoinInfo();
        setCurCoin(coinInfo);

        // 获取充值入账收益率配置
        doGetRechargeIncomeConfig();

        //打点
        doHitEvent("HOME_START")

        return () => {
            //打点
            doHitEvent("HOME_END")
        }
    }, []);

    // 点击 nav back
    const onHandleNavBackClick = () => {
        history.push('/mywalletlist');
    };

    // 点击 Transfer
    const onHandleMenuWithdraw = () => {
        history.push('/withdraw');
    };

    // 点击 Receive
    const onHandleMenuReceive = () => {
        history.push('/receive');
    };

    // 点击 Earn
    const onHandleMenuInvite = () => {
        history.push('/invite');
    };

    // 点击 today earn
    const onHandleTodayEarnClick = () => {
        history.push('/todayearn');
    }

    // 点击 invite earn
    const onHandleInviteEarnClick = () => {
        history.push('/invitedetail');
    };

    // 点击 today earn rules
    const onHandleTodayEarnRulesClick = () => {
        history.push('/todayearnrules');
    };

    // 点击 invite earn rules
    const onHandleInviteEarnRulesClick = () => {
        history.push('/inviteearnrules');
    };

    // 点击 invite withdraw
    const onHandleInviteWithdrawClick = (e) => {
        history.push('/withdrawforinvite');
        e.stopPropagation();
    };


    // 切换监听
    const onHandleSwiperIndexChanged = (index) => {
        console.log("切换监听: " + index)

    };


    // 获取充值入账收益率配置 返回
    const onDoGetRechargeIncomeConfigCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取充值入账收益率配置 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            if (data.length > 0) {
                // [
                //     {
                //         "min": "1",
                //         "max": "500",
                //         "rate": "0.02",
                //         "level": "BRONZE"
                //     },
                //     {
                //         "min": "501",
                //         "max": "2000",
                //         "rate": "0.03",
                //         "level": "GOLD"
                //     },
                //     {
                //         "min": "2001",
                //         "max": "5000",
                //         "rate": "0.05",
                //         "level": "PLATINUM"
                //     },
                //     {
                //         "min": "5001",
                //         "max": "9999999999",
                //         "rate": "0.08",
                //         "level": "DIAMOND"
                //     }
                // ]

                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    item.isValidData = false;
                    item.remindTimes = "0";
                    item.todayAmount = "0";
                    item.todayIncome = "0";
                    item.totalTimes = "0";
                    item.process = 0;
                    item.rate = toPercentageString(item.rate || "0");

                    if (EarnLevel.BRONZE === item.level) {
                        item.icon = icon_earn_level_1;

                    } else if (EarnLevel.GOLD === item.level) {
                        item.icon = icon_earn_level_2;

                    } else if (EarnLevel.PLATINUM === item.level) {
                        item.icon = icon_earn_level_3;

                    } else if (EarnLevel.DIAMOND === item.level) {
                        item.icon = icon_earn_level_4;
                    }
                }

                // 更新
                curLevelListTemp = data;
                setCurLevelList(data);

                setTimeout(() => {
                    // 获取转入收益总览
                    const coinInfo = getCoinInfo();
                    const coninType = coinInfo.coinType || "";
                    doGetTransferInEarn(coninType);
                    doGetInviteFriendEarn(coninType);
                }, 500);
            }
        }
    };


    // 获取转入收益总览 返回
    const onDoGetTransferInEarnCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取转入收益总览 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            // {
            //     "level": "BRONZE",
            //     "todayIncome": "0.00",
            //     "incomeRate": 0.02,
            //     "totalTimes": 3,
            //     "remindTimes": 3,
            //     "todayAmount": "0E-8",
            //     "nextAmount": "500"
            // }

            let newLevelList = [...curLevelListTemp];
            let scrollIndex = 0
            for (let index = 0; index < newLevelList.length; index++) {
                let item = newLevelList[index];
                //公共数据
                let todayAmount = (parseFloat(data.todayAmount) || 0) + "";
                data.todayAmount = todayAmount;

                let todayAmountF = parseFloat(data.todayAmount) || 0;
                let maxAmountF = parseFloat(data.max) || 0;
                if (maxAmountF <= 0) {
                    item.process = 0;
                } else {
                    item.process = (todayAmountF / maxAmountF);
                }

                item.remindTimes = data.remindTimes || "0";
                item.todayAmount = data.todayAmount || "0";
                item.todayIncome = data.todayIncome || "0";
                item.totalTimes = data.totalTimes || "0";

                if (item.level === data.level) {
                    item.isValidData = true;
                    scrollIndex = index;

                } else {
                    item.isValidData = false;
                }
            }
            console.log(newLevelList)

            // 更新
            setCurScrollIndex(scrollIndex);
            setCurLevelList(newLevelList);
        }
    };

    // 获取邀请好友收益总览 返回
    const onDoGetInviteFriendEarnCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取邀请好友收益总览 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            // {
            //     "incomeRate": 0.2,
            //     "myIncome": 0,
            //     "inviteNum": 0,
            //     "friendIncome": 0
            // }
            data.incomeRate = toPercentageString(data.incomeRate || "0");


            // 更新
            setCurInviteEarn(data);
        }
    };

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取充值入账收益率配置
    const doGetRechargeIncomeConfig = async () => {
        console.log("doGetRechargeIncomeConfig: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getRechargeIncomeConfig(onDoGetRechargeIncomeConfigCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取转入收益总览
    const doGetTransferInEarn = async (coinType) => {
        console.log("doGetTransferInEarn: ");

        if (!coinType || coinType.length <= 0) {
            Toast.show(curLang.earnTheCoinTypeCanNotBeNull);
            return;
        }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getTransferInEarn(coinType, onDoGetTransferInEarnCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }


    // 获取邀请好友收益总览
    const doGetInviteFriendEarn = async (coinType) => {
        console.log("doGetInviteFriendEarn: ");

        if (!coinType || coinType.length <= 0) {
            Toast.show(curLang.earnTheCoinTypeCanNotBeNull);
            return;
        }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getInviteFriendEarn(coinType, onDoGetInviteFriendEarnCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    const onRendSwiperItem = () => {
        if (curLevelList.length === 0) {
            return (
                <Swiper.Item key={0}><div></div></Swiper.Item>)
        }

        let list = [];
        for (let index = 0; index < curLevelList.length; index++) {
            let item = curLevelList[index];

            let bgType = item.level;
            let bgStyle = styles.earnearnSwiperItemContentBg;
            let barStyle = styles.earnearnSwiperItemRowProcessBarCurrent;
            if (EarnLevel.GOLD === item.level) {
                bgStyle = styles.earnearnSwiperItemContentBg2;
                barStyle = styles.earnearnSwiperItemRowProcessBarCurrent2;

            } else if (EarnLevel.PLATINUM === item.level) {
                bgStyle = styles.earnearnSwiperItemContentBg3;
                barStyle = styles.earnearnSwiperItemRowProcessBarCurrent3;

            } else if (EarnLevel.DIAMOND === item.level) {
                bgStyle = styles.earnearnSwiperItemContentBg4;
                barStyle = styles.earnearnSwiperItemRowProcessBarCurrent4;
            }

            let process = 5;
            if (item.process > 0.06) {
                process = item.process * 100;
            }

            // 测试
            // if (index === 1) {
            //     process = 60;
            // } else if (index === 2) {
            //     process = 40;
            // } else if (index === 3) {
            //     process = 90;
            // }
            const processWidth = (process + "%");

            let icon = item.icon;
            list.push(
                <Swiper.Item key={index}>
                    <div className={styles.earnearnSwiperItem}>
                        <div className={`${styles.earnearnSwiperItemContentBg} ${bgStyle}`}>
                            <div className={styles.earnearnSwiperItemContent}>
                                <div className={styles.earnearnSwiperItemRow}>
                                    <div className={styles.earnearnSwiperItemRowTitle}>{curLang.earnCurrentEarnToday}</div>
                                    <div className={styles.earnearnSwiperItemRowValue}>{item.todayIncome} <span style={{ fontSize: '10px', marginLeft: '2px', fontWeight: 'normal' }}>USDT</span></div>
                                </div>

                                <div className={styles.earnearnSwiperItemRow}>
                                    <div className={styles.earnearnSwiperItemRowTitle}>{curLang.earnEarnRatio}</div>
                                    <div className={styles.earnearnSwiperItemRowValue}>{item.rate}</div>
                                </div>

                                <div className={styles.earnearnSwiperItemRow}>
                                    <div className={styles.earnearnSwiperItemRowTitle}>{curLang.earnWithdrawalTimes}</div>
                                    <div className={styles.earnearnSwiperItemRowValue}>{item.remindTimes}/{item.totalTimes}</div>
                                </div>

                                <div className={styles.earnearnSwiperItemRowProcessBar}>
                                    <div className={styles.earnearnSwiperItemRowProcessBarFull}>
                                        <div className={`${styles.earnearnSwiperItemRowProcessBarCurrent} ${barStyle}`} style={{ width: processWidth }}></div>
                                    </div>
                                    <div className={styles.earnearnSwiperItemRowProcessBarValue}>{item.max} <span style={{ fontSize: '10px', marginLeft: '2px', fontWeight: 'normal' }}>USDT</span></div>
                                </div>

                                <div className={styles.earnearnSwiperItemRowProcessBar}>
                                    <div className={styles.earnearnSwiperItemRowTitle}>{curLang.earnMaxSingleTransaction}</div>
                                    <div className={styles.earnearnSwiperItemRowValue}>{item.todayAmount} <span style={{ fontSize: '10px', marginLeft: '2px', fontWeight: 'normal' }}>USDT</span></div>
                                </div>
                            </div>
                            <img className={styles.earnearnSwiperItemImage} src={icon} alt="" />

                            <div className={styles.earnearnSwiperItemType}>{bgType}</div>

                            {item.isValidData && <div className={styles.earnearnSwiperItemCurrentLevel}>{curLang.earnCurrentLevel}</div>}
                        </div>
                    </div>
                </Swiper.Item>
            );
        }
        return list;
    }


    return (
        <div className="pageRoot ">
            <NavigateBar theme="white" showLogout={false} leftIcon={icon_nav_menu} rightIcon={icon_nav_add_app} onAddFavorite={() => { setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskVisible(true) }} onGoBack={onHandleNavBackClick}>{curCoin.name}</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull pageContentPaddingHorizontal16px">
                {/* transfer earn 模块 */}
                <div className={styles.earnTransferEarn}>
                    {/* 标题 */}
                    <div className={styles.earnTitleRow}>
                        <div className={styles.earnTitle}>{curLang.earnTransferInEarn}</div>
                        <div className={styles.earnTitleRule} onClick={onHandleTodayEarnRulesClick}>{curLang.earnRuleDetails}</div>
                    </div>

                    {/* 等级 */}
                    <div className={styles.earnTransferEarnSwipe} onClick={onHandleTodayEarnClick}>
                        <Swiper
                            style={{
                                '--border-radius': '8px',
                            }}
                            stuckAtBoundary={false}
                            slideSize={90}
                            trackOffset={5}
                            indicator={() => null}
                            onIndexChange={onHandleSwiperIndexChanged}
                            defaultIndex={curScrollIndex}>
                            {onRendSwiperItem()}
                        </Swiper>
                    </div>
                </div>

                {/* 菜单 列表 */}
                <div className="pageContentRowFull pageMarginTop10px">
                    <div className="pageContentRowFull pageCardGrayBorder">
                        {/* Transfer */}
                        <div className={styles.earnMenuColumn} onClick={onHandleMenuWithdraw}>
                            <img className={styles.earnMenuImage} alt="" src={icon_earn_withdraw} />
                            <div className={styles.earnMenuTitle}>{curLang.earnWithdraw}</div>
                        </div>

                        {/* Receive */}
                        <div className={styles.earnMenuColumn} onClick={onHandleMenuInvite}>
                            <img className={styles.earnMenuImage} alt="" src={icon_earn_invite} />
                            <div className={styles.earnMenuTitle}>{curLang.earnInvite}</div>
                        </div>

                        {/* Earn */}
                        <div className={styles.earnMenuColumn} onClick={onHandleMenuReceive}>
                            <img className={styles.earnMenuImage} alt="" src={icon_receive} />
                            <div className={styles.earnMenuTitle}>{curLang.earnReceive}</div>
                        </div>
                    </div>
                </div>

                {/* invite earn 模块 */}
                <div className={styles.earnInviteEarn}>
                    {/* 标题 */}
                    <div className={styles.earnTitleRow}>
                        <div className={styles.earnTitle}>{curLang.earnInviteEarn}</div>
                        <div className={styles.earnTitleRule} onClick={onHandleInviteEarnRulesClick}>{curLang.earnRuleDetails}</div>
                    </div>

                    {/* 等级 */}
                    <div className={`${styles.earnInviteEarnContent} pageMarginTop10px`} onClick={onHandleInviteEarnClick}>
                        <div className={`${styles.earnInviteEarnMenuRow}`}>
                            <div className={styles.earnInviteEarnMenuRowTitle}>{curLang.earnInvitationRewardsRatio}</div>
                            <div className={styles.earnInviteEarnMenuRowValue}>{curInviteEarn.incomeRate}</div>
                        </div>

                        <div className={`${styles.earnInviteEarnMenuRow} pageMarginTop16px`}>
                            <div className={styles.earnInviteEarnMenuRowTitle}>{curLang.earnInvitationRewards}</div>
                            <div className={styles.earnInviteEarnMenuRowValue}>{curInviteEarn.myIncome} USDT</div>
                        </div>

                        <div className={styles.earnInviteEarnLine}></div>

                        <div className={`${styles.earnInviteEarnMenuRow} pageMarginTop16px`}>
                            <div className={styles.earnInviteEarnMenuRowTitle}>{curLang.earnInvitedNumber}</div>
                            <div className={styles.earnInviteEarnMenuRowValue}>{curInviteEarn.inviteNum}</div>
                        </div>

                        <div className={`${styles.earnInviteEarnMenuRow} pageMarginTop16px`}>
                            <div className={styles.earnInviteEarnMenuRowTitle}>{curLang.earnFriendsEarn}</div>
                            <div className={styles.earnInviteEarnMenuRowValue}>{curInviteEarn.friendIncome} USDT</div>
                        </div>

                        <div className={styles.earnInviteEarnWithdraw} onClick={e => { onHandleInviteWithdrawClick(e); }}>{curLang.earnWithdraw}</div>
                    </div>
                </div>
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"> </div>

            {/* tab bar */}
            <BottomTabBar page="earn" />

            {/* 添加桌面快捷方式 */}
            <AddToHomeDialog visible={addHomeMaskVisible} onClose={() => { setAddHomeMaskVisible(false) }}></AddToHomeDialog>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}